package com.ke.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ke.pojo.BaseResp;
import com.ke.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 拦截器,需要用户登陆过后才能访问的页面
 * @author bochen
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //解决文件上传无法跨域问题
        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }
        Cookie[] cookies = request.getCookies();
        String token="";
        if (cookies!=null){
            for (Cookie cookie:cookies){
                if ("token".equals(cookie.getName())){
                    token=cookie.getValue();
                }
            }
        }
        if (token.isEmpty()){
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            response.getWriter().write(JSONObject.toJSONString(new BaseResp(1,"用户未登录")));
            return false;
        }
        Map<String, String> map = jwtUtils.verifyToken(token);
        if (map==null){
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            response.getWriter().write(JSONObject.toJSONString(new BaseResp(1,"用户登录过期")));
            return false;
        }
        request.setAttribute("username",map.get("username"));
        request.setAttribute("id",map.get("id"));
        return true;
    }
}
